package com.example.web.websystem.service;

import com.example.web.websystem.dao.model.SysUserDO;
import com.example.web.websystem.response.BusinessError;
import com.example.web.websystem.response.GlobalCodeEnum;
import com.example.web.websystem.token.manage.TokenHandle;
import com.example.web.websystem.token.manage.TokenObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by YangGang on 2021/9/15 11:38。
 */
@Service
public class SysLoginService {
    @Autowired
    private SysUserService sysUserService;


    /**
     * 校验web登陆
     *
     * @param username
     * @param password
     * @return token
     */
    public String checkWebLogin(String username, String password) {
        // 1，通过账号密码获取user
        SysUserDO sysUser = sysUserService.getSysUserByUsernamePassword(username, password);
        if (sysUser == null || sysUser.getUserId() == null) {
            throw new BusinessError(GlobalCodeEnum.LOGIN_CHECK_ERROR);
        }
        //2，是否是系统管理员
        if (!sysUser.getIsAdministrator()) {
            // 3，检查是否存在角色
            if (sysUser.getRoleIds() == null || sysUser.getRoleIds().trim().isEmpty()) {
                throw new BusinessError(GlobalCodeEnum.NO_ROLE);
            }
        }
        // 4，创建token
        TokenObject tokenObject = new TokenObject(
                sysUser.getUserId(), sysUser.getGroupId(), sysUser.getIsAdministrator());
        String token = TokenHandle.createToken(tokenObject);
        return token;
    }


}
